import { createAtom, useStore } from "@/util/hooks";
import { Tree } from "@arco-design/web-react";
import { PreviewTreeStore } from "./inteface";
import _ from "lodash";

export const PreviewTreeAtom = createAtom<PreviewTreeStore>({
  data: [],
  originDataList: [],
});

export const PreviewTree = () => {
  const store = useStore(PreviewTreeAtom);
  if (_.isEmpty(store.value.data)) {
    return <></>;
  }
  // 树仅在第一次渲染时才会自动展开节点
  // 所以在没有数据时，不需要渲染
  return (
    <Tree
      blockNode
      showLine
      treeData={store.value.data}
      selectedKeys={
        store.value.selectedKey ? [store.value.selectedKey] : undefined
      }
      onSelect={(selectedKeys, { selectedNodes }) => {
        const selectedKey = selectedKeys[0];
        const selectedNode = selectedNodes[0].props;
        store.updateStoreAll((prev) => {
          const selected =
            !!prev.selectedKey && prev.selectedKey === selectedKey;
          const selectedRecord = selected
            ? undefined
            : (selectedNode as any).data;
          return {
            ...prev,
            selectedKey: selected ? undefined : selectedKey,
            selectedRecord,
          };
        });
      }}
    />
  );
};
